package com.example.fragmenttest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button toastButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toastButton = findViewById(R.id.toast);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .add(R.id.fragment1,new Fragment1())
                .addToBackStack(null)
                .commit();
        fragmentManager.beginTransaction()
                .add(R.id.fragment2,new Fragment2())
                .addToBackStack(null)
                .commit();

    }

    @Override
    protected void onStart() {
        super.onStart();
        toastButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment2 fragment = (Fragment2) MainActivity.this.getSupportFragmentManager()
                        .findFragmentById(R.id.fragment2);
                fragment.toastMessage("This message from fragment2");
            }
        });
    }
}
